"""
查询实时告警，返回具体告警信息。

正常时，返回：
{'total': 0, 'result': []}
出现故障时，返回故障数量及详细信息：
{'total': 1, 'result': [{'alarm_service_log': None, 'recovery_time': '2023-03-17 02:53:03', 'alarm_level': 'major', 'class_id': '0x02050105', 'alarm_module': 'NAS服务器', 'alarm_time': '2023-03-17 02:47:53', 'alarm_content': '节点ONEStor3 MDS平均每秒请求数为8283.4，告警阈值：4000，当前请求数达到或者超过告警阈值。', 'nodepool_name': 'nodepool', 'alarm_status': 'auto_recovery', 'confirm_time': None, 'index_id': 1183, 'alarm_source': 'ONEStor3'}]}

重要输出参数解释
total           --  查询出的告警总数
recovery_time   --  告警恢复时间
alarm_level     --  critical（紧急）、major（重要）、minor（一般）、warning（提示）、self_define（自定义）
alarm_time      --  告警产生时间
alarm_content   --  告警内容
alarm_status    --  un_recovery（未恢复）, auto_recovery（已恢复）, user_confirm（已确认）
alarm_source    --  告警源
"""

import requests
import json
import re


def get_h3c_alarm_real_data(ip):
    # 拼接成登陆url
    base_url = "http://"+ ip
    request_url = "/api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 获取响应头信息
    # print(res.headers)
    set_cookie = res.headers.get('Set-Cookie')
    text_set_cookie = re.split('[;,=\']', set_cookie)

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    xsrf_token_value = text_set_cookie[1].strip()

    cookie_value = 'calamari_sessionid=' + text_set_cookie[12] + ';' + 'XSRF-TOKEN=' + xsrf_token_value

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url

    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成请求URL
    cluster_alarm_real_1 = "/api/v3/onestor/"
    cluster_alarm_real_2 = "/plat/alarm/all"
    cluster_alarm_real_url = base_url + cluster_alarm_real_1 + cluster_id + cluster_alarm_real_2
    # print(cluster_alarm_real_url)

    # 请求参数
    request_data = {
        "alarm_level": [
            "warning",
            "minor",
            "major",
            "critical",
            "self_define"
        ],
        "alarm_module": [
            "DEVICE",
            "CLUSTER",
            "NET",
            "OS",
            "NAS"
        ],
        "alarm_sort": "desc",
        "alarm_state": "current",
        "alarm_status": [
            "un_recovery",
        ],
        "begin_time": "",
        "content_key": "",
        "end_time": "",
        "key_word": "",
        "language": "zh-cn",
        "limit": 1,
        "offset": 0,
        # "nodepool_name": ["nodepool"]
    }

    # 发送POST请求，得到返回数据
    cluster_alarm_real_res = requests.post(
        url=cluster_alarm_real_url,
        data=json.dumps(request_data),
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    cluster_alarm_real_data = cluster_alarm_real_res.json()

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    return cluster_alarm_real_data['data']


if __name__ == '__main__':
    
    ip_list = ['ip地址']
    alarm_message_list = []
    for ip in ip_list:
        alarm_message = get_h3c_alarm_real_data(ip)
        alarm_message_list.append(alarm_message)
    print(alarm_message_list)